package com.csxy.yhj.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csxy.yhj.entity.EduSubject;
import com.csxy.yhj.entity.excel.SubjectData;
import com.csxy.yhj.exception.MyException;
import com.csxy.yhj.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    public SubjectExcelListener() {
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
       //判断Excel中一级分类是否为空，若无内容则抛出自定义异常
        if (subjectData == null){
            throw new MyException(20001,"添加失败");
        }

        //一行一行读取，每次读取有连个值，第一个值为一级分类名称，第二个值为二级分类名称
        //判断是否有一级分类重复，若有则不添加
        EduSubject existOneSubject = this.existOneSubject(eduSubjectService,subjectData.getOneSubjectName());
        if (existOneSubject == null){  //没有相同的一级分类，进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");  //设置一级分类id,0代表为一级分类
            existOneSubject.setTitle(subjectData.getOneSubjectName()); //设置一级分类名
            eduSubjectService.save(existOneSubject);  //给数据库添加一级分类
        }

        //获取一级分类的id值
        String parent_id = existOneSubject.getId();
        //判断二级分类是否重复，若有则不添加
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService,subjectData.getTwoSubjectName(), parent_id);
        if (existTwoSubject == null){   //没有相同的二级分类，进行添加
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(parent_id); //设置二级分类id,0代表为一级分类
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());//设置二级分类名
            eduSubjectService.save(existTwoSubject);  //给数据库添加二级分类
        }

    }

    //判断数据库中是否有相同的一级分类,不能重复添加
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name)
                .eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断数据库中是否有相同二级分类,不能重复添加
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String parentId){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name)
                .eq("parent_id",parentId);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
